package com.book.controller;

import cn.hutool.core.lang.Snowflake;
import com.book.entity.BookOrder;
import com.book.entity.BookOrderItem;
import com.book.service.BookOrderService;
import com.book.util.JsonResult;
import com.book.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author SuperYu  2024/7/30
 */

@Controller
@RequestMapping("/order")
@Slf4j
public class BookOrderController {
    @Resource
    BookOrderService bookOrderService;


    @PostMapping("/addOrder")
    public String getOrderNum(int addressId, int[] bookId, int[] buyCount, String[] subTotal, int[] cartId,  String total, HttpSession session) {
        // 从数据库查出，当前用户的购物车数据
        Long userId = (Long) session.getAttribute("loginUserId");
        // 订单编号通过雪花算法算出来。
        long orderId = new Snowflake().nextId();

        // 一个订单
        BookOrder bookOrder = new BookOrder(orderId, userId, addressId, new BigDecimal(total), (byte)0);

        // 多个详情
        ArrayList<BookOrderItem> list = new ArrayList();
        for (int i = 0; i < bookId.length; i++) {
            list.add(new BookOrderItem(orderId,new Long(bookId[i]),buyCount[i],new BigDecimal(subTotal[i])));
        }

        int i = bookOrderService.addOrder(bookOrder, list);

        if(i > 0){
            // 说明订单添加成功了，这个时候，再删除已经下了单的购物车数据。
            // bookCartService.deleteByIds(cartId)  //
        }

        return "order";
    }

}
